package org.friut.util;

import java.util.ArrayList;
import java.util.List;

public class ListUtils {

	/**
	 * Sub list
	 * 
	 * @param <T>
	 * @param start
	 * @param limit
	 * @return
	 */
	public static <T> List<T> subList(List<T> list, int start, int limit) {
		if (start > list.size()) {
			return new ArrayList<T>();
		} else {
			int end = Math.min(list.size(), start + limit);
			return list.subList(start, end);
		}
	}
	
	/**
	 * Sub list by page number
	 * 
	 * @param <T>
	 * @param list
	 * @param page
	 * @return
	 */
	public static <T> List<T> subListByPage(List<T> list, int page, int numPerPage) {
		int start = (page - 1) * numPerPage;
		int end = start + numPerPage;
		if (list.size() < end)
			end = list.size();
		
		return list.subList(start, end);
	}
	
	/**
	 * Select random element
	 * 
	 * @param <T>
	 * @param list
	 * @return 
	 */
	public static <T> T selectRandomElement(List<T> list) {
		if (list == null || list.isEmpty()) {
			return null;
		}
		
		int randIdx = IntegerUtils.generateRandomSeed(0, list.size() - 1);
		return list.get(randIdx);
	}
	
	/**
	 * Select random element by count
	 * 
	 * @param <T>
	 * @param list
	 * @return 
	 */
	public static <T> List<T> selectNorepeatRandomElements(List<T> list, int count) {
		List<T> randomList = new ArrayList<T>();
		if (list == null || list.isEmpty()) {
			return randomList;
		}
		
		// Get random index
		count = Math.min(list.size(), count);
		int[] indexs = IntegerUtils.generateNorepeatRandomSeed(0, list.size() - 1, count);	
		
		// Get random elements
		for (int idx : indexs) {
			T obj = list.get(idx);
			randomList.add(obj);
		}
		
		return randomList;
	}
}
